package reflex.proxy;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2019-06-08 15:44:00
 */

interface Human{
    void info();

    void fly();
}

//被代理类
class SuperMan implements Human{
    @Override
    public void info() {
        System.out.println("我是超人！");
    }

    @Override
    public void fly() {
        System.out.println("I believe I can fly!");
    }
}

class HumanUtil{
    public void method1(){
        System.out.println("方法一");
    }

    public void method2(){
        System.out.println("方法二");
    }
}


class MyInvocationHandler implements InvocationHandler{
    //被代理对象的申明
    Object obj;

    public void setObj(Object obj){
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        HumanUtil h = new HumanUtil();
        h.method1();

        Object res = method.invoke(obj, args);

        h.method2();

        return res;
    }
}

//动态的创建一个代理类的对象
class MyProxy{
    public static Object getProxyInstance(Object obj){
        MyInvocationHandler handler = new MyInvocationHandler();
        handler.setObj(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
    }
}

public class TestAop {

    @Test
    public void test01(){
        //创建一个被代理类的对象
        SuperMan superMan = new SuperMan();
        //返回一个代理类的读喜庆
        Object obj = MyProxy.getProxyInstance(superMan);
        Human human = (Human) obj;
        //通过代理类的方法调用重写的方法
        human.info();
        System.out.println();
        human.fly();
    }

}
